﻿// 非立即执行版
function debounce(func, wait) {
    let timer;
    return function() {
        let context = this; // 注意 this 指向
        let args = arguments; // arguments中存着e

        if (timer) clearTimeout(timer);

        timer = setTimeout(() => {
            func.apply(this, args)
        }, wait)
    }
}
// 立即执行版
function debounce2(func, wait) {
    let timer;
    return function() {
        let context = this; // 这边的 this 指向谁?
        let args = arguments; // arguments中存着e
        if (timer) clearTimeout(timer);
        let callNow = !timer;
        timer = setTimeout(() => {
            timer = null;
        }, wait)
        if (callNow) func.apply(context, args);
    }
}

// 合成版
/**
 * @desc 函数防抖
 * @param func 目标函数
 * @param wait 延迟执行毫秒数
 * @param immediate true - 立即执行， false - 延迟执行
 */
function debounce3(func, wait, immediate) {
    let timer;
    return function() {
        let context = this,
            args = arguments;

        if (timer) clearTimeout(timer);
        if (immediate) {
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, wait);
            if (callNow) func.apply(context, args);
        } else {
            timer  = setTimeout(() => {
                func.apply
            }, wait)
        }
    }
}